//
//  ContactsViewController.swift
//  EasyDana
//
//  Created by mac on 2024/10/16.
//

import UIKit
import RxSwift
import RxCocoa

class ContactsViewController: UIViewController {
    
    private let bag = DisposeBag()
    
    var product_id = ""//产品ID
    
    var naviTitle: String = ""
    
    var step: Int = -1
    
    var totalStep = 0
    
    private let getApi: Api = .getContacts
    
    private let saveApi: Api = .saveContacts
    
    private let source: BehaviorRelay<[BehaviorRelay<ContactsModel>]> = BehaviorRelay(value: [])
    
    let riskType = 6
    
    private var beginDate = Date()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.configView()
    }
    
    private func stepView(currentStep: Int, totalStep: Int)->UIView {
        let view = UIStackView()
        view.axis = .horizontal
        view.distribution = .fill
        view.alignment = .center
        func genStepDot(step: Int, done: Bool) -> UIView {
            let stepView = UIView()
            var image: String = "authen_complete"
            if (!done) {
                image = "authen_not_complete"
            }
            let imageView = UIImageView(image: UIImage(named: image))
            stepView.addSubview(imageView)
            imageView.snp.makeConstraints { make in
                make.edges.equalToSuperview()
                make.width.height.equalTo(32)
            }
            let nameLabel = UILabel()
            stepView.addSubview(nameLabel)
            nameLabel.text = "\(step)"
            nameLabel.textColor = UIColor.white
            nameLabel.font = UIFont.systemFont(ofSize: 16)
            nameLabel.snp.makeConstraints { make in
                make.center.equalToSuperview()
            }
            return stepView
        }
        func genLine(done: Bool) -> UIImageView {
            if (done) {
                return UIImageView(image: UIImage(named: "authen_complete_line"))
            } else {
                return UIImageView(image: UIImage(named: "authen_not_complete_line"))
            }
        }
        for i in 1 ... totalStep {
            if i <= currentStep {
                let dotView = genStepDot(step: i, done: true)
                view.addArrangedSubview(dotView)
            } else {
                let dotView = genStepDot(step: i, done: false)
                view.addArrangedSubview(dotView)
            }
            if (i != totalStep) {
                let lineView = genLine(done: i < currentStep)
                view.addArrangedSubview(lineView)
            }
        }
        return view
    }
    
    private func configView() {
        self.view.backgroundColor = UIColor.white//UIColor.hex(with: "#F7F7F7")
        let topView = UIView()
        self.view.addSubview(topView)
        let naviBar = NavigationBar()
        naviBar.title = naviTitle
        naviBar.titleColor = UIColor.hex(with: "#121001")
        naviBar.backColor = UIColor.hex(with: "#121001")
        self.view.addSubview(naviBar)
        naviBar.backClicked
            .subscribe(onNext: { [weak self] in
                self?.navigationController?.popViewController(animated: true)
            })
            .disposed(by: self.bag)
        naviBar.snp.makeConstraints { make in
            make.top.equalTo(self.view.snp.topMargin)
            make.left.right.equalToSuperview()
            make.height.equalTo(47)
        }
        let stepView = self.stepView(currentStep: self.step, totalStep: self.totalStep)
        self.view.addSubview(stepView)
        stepView.snp.makeConstraints { make in
            make.top.equalTo(naviBar.snp.bottom).offset(15)
            make.centerX.equalToSuperview()
        }
        let contentView = UIView()
        self.view.addSubview(contentView)
        contentView.backgroundColor = UIColor.hex(with: "#f7f7f7")
        contentView.snp.makeConstraints { make in
            make.left.bottom.right.equalToSuperview()
            make.top.equalTo(stepView.snp.bottom).offset(15)
        }
        let nextButton = UIButton(type: .system)
        nextButton.setImage(UIImage(named: "authen_next_step")?.withRenderingMode(.alwaysOriginal), for: .normal)
        contentView.addSubview(nextButton)
        nextButton.snp.makeConstraints { make in
            make.centerX.equalToSuperview()
            make.bottom.equalTo(contentView.snp.bottomMargin).offset(-10)
        }
        nextButton.addTarget(self, action: #selector(nextAction(button:)), for: .touchUpInside)
        
        let scrollView = UIScrollView()
        scrollView.backgroundColor = contentView.backgroundColor
        scrollView.showsVerticalScrollIndicator = false
        scrollView.showsHorizontalScrollIndicator = false
        contentView.addSubview(scrollView)
        scrollView.snp.makeConstraints { make in
            make.top.left.right.equalToSuperview()
            make.bottom.equalTo(nextButton.snp.top).offset(-10)
        }
        let contentStackView = UIStackView()
        scrollView.addSubview(contentStackView)
        contentStackView.axis = .vertical
        contentStackView.spacing = 20
        contentStackView.alignment = .fill
        contentStackView.distribution = .fillEqually
        contentStackView.snp.makeConstraints { make in
            make.top.equalToSuperview().offset(15)
            make.left.equalToSuperview().offset(15)
            make.right.equalToSuperview().offset(-15)
            make.left.equalTo(self.view).offset(15)
            make.right.equalTo(self.view).offset(-15)
        }
        self.source
            .observe(on: MainScheduler.instance)
            .map({ models in
                var views: [ContactView] = []
                for (index, model) in models.enumerated() {
                    let view = ContactView(model: model, index: index) { observable in
                        
                    }
                    views.append(view)
                }
                return views
            })
            .subscribe(onNext: { src in
                let subviews = contentStackView.arrangedSubviews
                subviews.forEach { view in
                    view.removeFromSuperview()
                }
                src.forEach { view in
                    contentStackView.addArrangedSubview(view)
                }
                contentStackView.snp.remakeConstraints { make in
                    make.top.equalToSuperview().offset(15)
                    make.left.equalToSuperview().offset(15)
                    make.right.equalToSuperview().offset(-15)
                    make.left.equalTo(self.view).offset(15)
                    make.right.equalTo(self.view).offset(-15)
                    make.height.equalTo(200 * src.count)
                    make.bottom.equalToSuperview()
                }
            })
            .disposed(by: self.bag)
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        self.getData()
    }
    
    @objc private func nextAction(button: UIButton) {
        Task {
            do {
                self.showLoading(text: nil)
                var param: [String: Any] = ["guns": self.product_id]
                let belles = self.source.value.map({ model in
                    return ["th": model.value.th, "representative": model.value.representative, "pleasantly": model.value.pleasantly]
                })
                let jsonData = try JSONEncoder().encode(belles)
                let str = String(data: jsonData, encoding: .utf8)
                param["belles"] = str
                let res = try await HTTPManager.default.post(path: self.saveApi, param: param, dataType: [Int].self)
                if (res.code == 0) {
                    UploadStasticManager.default.uploadRiskPoint(type: 6, beginTime: self.beginDate)
                    self.hideLoading()
                    self.navigationController?.popViewController(animated: true)
                } else {
                    self.hideLoading()
                    self.show(toast: res.state)
                }
            } catch {
                self.hideLoading()
            }
        }
    }
    
    private func getData() {
        Task {
            struct ViiiModel: Codable {
                let viii: [ContactsModel]
            }
            do {
                self.showLoading(text: nil)
                let res = try await HTTPManager.default.post(path: self.getApi, param: ["guns": self.product_id], dataType: ViiiModel.self)
                self.hideLoading()
                if res.code == 0 {
                    let src = res.data!.viii.map { model in
                        return BehaviorRelay(value: model)
                    }
                    self.source.accept(src)
                } else {
                    self.show(toast: res.state)
                }
            } catch {
                print(error)
                self.hideLoading()
                
            }
        }
    }

}
